import java.util.LinkedList;
import java.util.List;

public class Day09 {
    // 从尾到头打印链表
    public int[] reverseBookList(ListNode head) {
        List<Integer> list = new LinkedList<>();
        while (head != null) {
            list.add(0, head.val);
            head = head.next;
        }
        int[] ret = new int[list.size()];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = list.remove(0);
        }
        return ret;
    }

    public static void main(String[] args) {
        Day09 day09 = new Day09();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(2);
        head.next.next.next.next.next = new ListNode(1);
        day09.removeDuplicateNodes(head);
    }

    public ListNode removeDuplicateNodes(ListNode head) {
        if(head == null) {
            return null;
        }

        ListNode prev = head;
        ListNode cur = head.next;

        while(cur != null) {
            if(isContain(head, cur)) {
                // 删除
                prev.next = cur.next;
            } else {
                prev = cur;
            }
            cur = cur.next;
        }

        return head;
    }

    private boolean isContain(ListNode head, ListNode cur) {
        while(head != cur) {
            if(head.val == cur.val) {
                return true;
            }
            head = head.next;
        }
        return false;
    }
}


